package com.hongkuncheng.cms.controller.admin;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.helper.DirectoryHelper;
import com.hongkuncheng.cms.helper.FileHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.model.ColumnsReDepartment;
import com.hongkuncheng.cms.model.Department;
import com.hongkuncheng.cms.model.Zhuanti;
import com.hongkuncheng.cms.model.Columns;
import com.hongkuncheng.cms.model.ColumnsType;
import com.hongkuncheng.cms.model.Datamodel;
import com.hongkuncheng.cms.model.Webinfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 栏目管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/columns")
public class AcolumnsController extends BaseController {

    // 栏目列表
    @RequestMapping
    public String index() {
        // 一级菜单
        List<Columns> columns1es = factorySession.createCriteria(Columns.class)
                .add(Restrictions.lt("columnsType.id", 6))
                .add(Restrictions.eq("parentId", 0))
                .addOrder(Order.asc("sort")).list();
        // 二级菜单
        Map<String, List<Columns>> columns2Maps = new HashMap<String, List<Columns>>();
        for (Columns columns1 : columns1es) {
            List<Columns> columns2Temps = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("parentId", columns1.getId()))
                    .addOrder(Order.asc("sort")).list();
            if (columns2Temps.size() > 0) columns2Maps.put(String.valueOf(columns1.getId()), columns2Temps);
        }
        request.setAttribute("columns1es", columns1es);
        request.setAttribute("columns2Maps", columns2Maps);
        return view();
    }

    // 栏目编辑
    @RequestMapping("edit")
    public String edit() {
        int parentId = request.getParameter("parentid") == null ? 0 : Integer.parseInt(request.getParameter("parentid"));
        int columnsId = request.getParameter("columnsid") == null ? 0 : Integer.parseInt(request.getParameter("columnsid"));
        Columns columns = columnsId == 0 ? new Columns() : factorySession.get(Columns.class, columnsId);
        if (columnsId == 0) {
            columns.setColumnsType(factorySession.load(ColumnsType.class, 1));
            columns.setAutosingle(true);
            Object uniqueResult = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("parentId", parentId))
                    .setProjection(Projections.max("sort")).uniqueResult();
            int maxSort = uniqueResult == null ? 0 : Integer.parseInt(uniqueResult.toString());
            columns.setDisplay(true);
            columns.setSort(++maxSort);
            columns.setParentId(parentId);
        }
        request.setAttribute("columns", columns);
        request.setAttribute("parentid", parentId);
        Criteria cirteriaColumnsType = factorySession.createCriteria(ColumnsType.class);
        cirteriaColumnsType.add(Restrictions.lt("id", 6));
        if (parentId > 0) cirteriaColumnsType.add(Restrictions.ne("id", 4));
        List<ColumnsType> columnstypes = cirteriaColumnsType.list();
        request.setAttribute("columnstypes", columnstypes);
        List<Datamodel> datamodels = factorySession.createCriteria(Datamodel.class)
                .add(Restrictions.eq("datamodelType.id", 3)).list();
        request.setAttribute("datamodels", datamodels);
        List<Zhuanti> zhuantis = factorySession.createCriteria(Zhuanti.class)
                .addOrder(Order.asc("sort")).list();
        request.setAttribute("zhuantis", zhuantis);
        webinfo = factorySession.get(Webinfo.class, 1);
        List<File> templatefiles = FileHelper.getFiles(applicationDirectory + "/template/" + webinfo.getTemplate());
        request.setAttribute("templatefiles", templatefiles);
        List<Integer> departmentIds = new ArrayList<Integer>();
        if (columns.getId() > 0) {
            for (ColumnsReDepartment crd : columns.getColumnsReDepartments())
                departmentIds.add(crd.getDepartment().getId());
        }
        request.setAttribute("departmentids", departmentIds);
        List<Department> departments = factorySession.createCriteria(Department.class)
                .add(Restrictions.isNotNull("urldirectory")).addOrder(Order.asc("sort")).list();
        request.setAttribute("departments", departments);
        return view();
    }

    // 栏目编辑处理
    @RequestMapping("editdo")
    @ResponseBody
    public void editdo() {
        checkAdminPermission("yunwei_webmaintain_colums");
        int parentId = Integer.parseInt(request.getParameter("parentid"));
        int columnsId = Integer.parseInt(request.getParameter("columnsid"));
        String name = request.getParameter("name");
        int exist = Integer.parseInt(factorySession.createCriteria(Columns.class)
                .add(Restrictions.eq("name", name)).add(Restrictions.ne("id", columnsId))
                .add(Restrictions.eq("parentId", parentId)).setProjection(Projections.count("id"))
                .uniqueResult().toString());
        if (exist > 0) {
            PageHelper.alertAndGoBack("栏目名称已存在，请重新输入");
            return;
        }
        int typeId = Integer.parseInt(request.getParameter("typeid"));
        String urldirectory = request.getParameter("urldirectory");
        if (typeId != 2 && typeId != 4) {
            if (parentId != 0 && DirectoryHelper.checkSpecial(urldirectory)) {
                PageHelper.alertAndGoBack("文件目录为系统特殊目录，您不能使用，请重新输入");
                return;
            }
            exist = Integer.parseInt(factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("urldirectory", urldirectory))
                    .add(Restrictions.ne("id", columnsId))
                    .add(Restrictions.eq("parentId", parentId))
                    .setProjection(Projections.count("id"))
                    .uniqueResult().toString());
            if (exist > 0) {
                PageHelper.alertAndGoBack("URL目录已在文档列表中存在，请重新输入");
                return;
            }
            exist = Integer.parseInt(factorySession.createCriteria(Zhuanti.class)
                    .add(Restrictions.eq("urldirectory", urldirectory))
                    .setProjection(Projections.count("id"))
                    .uniqueResult().toString());
            if (exist > 0) {
                PageHelper.alertAndGoBack("URL目录已在专题频道中存在，请重新输入");
                return;
            }
        }
        Columns columns = columnsId == 0 ? new Columns() :
                factorySession.load(Columns.class, columnsId, LockMode.PESSIMISTIC_WRITE);
        columns.setColumnsType(factorySession.load(ColumnsType.class, typeId));
        columns.setName(name);
        columns.setTarget(request.getParameter("target"));
        columns.setDisplay(Boolean.parseBoolean(request.getParameter("display")));
        columns.setSort(Integer.parseInt(request.getParameter("sort")));
        columns.setParentId(Integer.parseInt(request.getParameter("parentid")));
        switch (typeId) {
            case 1: // 文档列表
                columns.setUrldirectory(urldirectory);
                Integer datamodelId = Integer.parseInt(request.getParameter("datamodelid"));
                columns.setDatamodel(factorySession.load(Datamodel.class, datamodelId));
                String templatelist = request.getParameter("templatelist");
                columns.setTemplatelist(templatelist);
                String templatedetail = request.getParameter("templatedetail");
                columns.setTemplatedetail(templatedetail);
                columns.setAutosingle(Boolean.parseBoolean(request.getParameter("autosingle")));
                break;
            case 2: // 专题频道
                Integer zhuantiId = Integer.parseInt(request.getParameter("zhuantiid"));
                columns.setZhuanti(factorySession.load(Zhuanti.class, zhuantiId));
                break;
            case 3: // 其它内容
                columns.setUrldirectory(urldirectory);
                String templateother = request.getParameter("templateother");
                columns.setTemplateother(templateother);
                break;
            default: // 导航分组 + 自定义链接
                columns.setUrldirectory(urldirectory);
                break;
        }
        if (columnsId == 0) factorySession.save(columns);
        if (typeId == 1) {
            List<Integer> departmentIds = DataHelper.convertToIntegerList(request.getParameterValues("departmentids"));
            if (columnsId > 0) {
                if (columns.getColumnsReDepartments().size() > 0) {
                    // 删除原来的映射关系
                    List<Object> crds = new ArrayList<>();
                    for (ColumnsReDepartment crd : columns.getColumnsReDepartments()) {
                        if (!departmentIds.contains(crd.getDepartment().getId())) crds.add(crd);
                        else departmentIds.remove(Integer.valueOf(crd.getDepartment().getId()));
                    }
                    factorySession.delete(crds);
                }
            }
            if (departmentIds.size() > 0) {
                // 创建新的映射关系
                List<Department> departmentes = factorySession.createCriteria(Department.class)
                        .add(Restrictions.in("id", departmentIds)).list();
                for (Department department : departmentes) {
                    ColumnsReDepartment crd = new ColumnsReDepartment();
                    crd.setColumns(columns);
                    crd.setDepartment(department);
                    factorySession.save(crd);
                }
            }
        }
        recordLog((columnsId == 0 ? "新建" : "更新") + "栏目《" + columns.getName().trim() + "》");
        PageHelper.alertAndRedirect("保存成功", "./");
    }

    // 栏目删除
    @RequestMapping("delete")
    @ResponseBody
    public void delete() {
        checkAdminPermission("yunwei_webmaintain_colums");
        int columnsId = Integer.parseInt(request.getParameter("columnsid"));
        List<Columns> columnses = factorySession.createCriteria(Columns.class)
                .add(Restrictions.or(Restrictions.eq("id", columnsId),
                        Restrictions.eq("parentId", columnsId))).setLockMode(LockMode.PESSIMISTIC_WRITE).list();
        for (Columns columns : columnses) factorySession.delete(columns);
        recordLog("删除栏目《" + columnses.get(0).getName().trim() + "》");
        PageHelper.alertAndRedirect("删除成功", "./");
    }

}
